define(['./PageView', "jquery", '../libs/canlendar', '../libs/AjaxUtil', '../libs/CommonTools', '../libs/GetAction', '../libs/util'], function (PageView, $, Canlendar, AjaxUtil, CommonTools, GetAction, util) {

    return PageView.extend({
        events: {
            'click .left': 'back',
            'click .input-result-percent': 'focusOnPercentInput',
            'input #percent-input': 'btnStatus',
            'input #result-text': 'btnStatus',
            'click .save-btn': 'saveResult',
            'click .save-next-btn': 'saveResultGoNext',
        },
        initialize: function () {
            require('../../less/KeyResultsAdd.less');
            this.beginResultValue = '';
            this.beginProcessValue = '';
            this.target_id = '';
            this.key_id = '';
            this.getUrlParam();
        },
        render: function () {
            PageView.prototype.render.apply(this, arguments);
            var tpl = require('../templates/KeyResultAdd.html');
            this.$main = $('<div class="main"></div>');
            this.$wrap = $('<div class="content"></div>');
            this.$wrap.append(tpl);
            this.$main.append(this.$wrap);
            this.$el.append(this.$main);
            return this;
        },
        onRender: function () {
            var href = window.location.href;
            this.getUrlParam();
            if (href.indexOf("key_id") > 0) {
                this.setKeyInfo();
            } else {
                this.$el.find("#result-text").val("");
                this.$el.find("#percent-input").val("");
                this.$el.find(".title").text("新增关键结果");
                this.$el.find(".save-next-btn").show();
                this.$el.find(".save-btn").addClass("btn-disabled").removeClass('edit-save-btn');
                this.setBegin();
            }

            this.setPercent();

        },
        onResume: function () {
            this.onRender();
        },
        getUrlParam: function () {
            //获取URL上的参数
            var url = location.href;
            var index = url.indexOf("#");
            url = url.substr(index);
            var theRequest = {};

            //获取url中"?"符后的字串
            if (url.indexOf("?") != -1) {
                index = url.indexOf("?");
                var str = url.substr(index + 1);
                var strs = str.split("&");
                for (var i = 0; i < strs.length; i++) {
                    theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
                }
            }
            this.target_id = theRequest.target_id;
            this.key_id = theRequest.key_id;
        },
        setBegin: function () {
            //设置存储初始值
            this.beginResultValue = this.$el.find('#result-text').val();
            this.beginProcessValue = this.$el.find("#percent-input").val();
        },
        isChange: function () {
            var resultValue = this.$el.find('#result-text').val();
            var processValue = this.$el.find('#percent-input').val();
            if (resultValue == this.beginResultValue && processValue == this.beginProcessValue) {
                return false;
            } else {
                return true;
            }
        },
        setKeyInfo: function () {
            //编辑时页面渲染
            var keyResults = JSON.parse(sessionStorage.getItem("goalData")).keyResult;
            var keyId = this.key_id;
            var keyInfo;
            for (var i = 0; i < keyResults.length; i++) {
                if (keyResults[i].id == keyId) {
                    keyInfo = keyResults[i];
                    // break;
                }
            }

            this.$el.find("#result-text").val(keyInfo.description);
            this.$el.find("#percent-input").val(keyInfo.progress);
            this.$el.find(".title").text("编辑关键结果");
            this.$el.find(".save-next-btn").hide();
            this.$el.find(".save-btn").removeClass("btn-disabled").addClass("edit-save-btn");
            this.setBegin();
        },
        resetPage: function () {
            this.$el.find("#result-text").val("");
            this.$el.find("#percent-input").val("");
            this.$el.find(".btn").addClass("btn-disabled");
        },
        btnStatus: function () {
            var resultInput = this.$el.find('#result-text').val();
            var percentInput = this.$el.find('#percent-input').val();
            if (resultInput.length > 0 && percentInput.length > 0) {
                this.$el.find('.btn').removeClass('btn-disabled');
            }
            else {
                this.$el.find('.btn').addClass('btn-disabled');
            }
        },
        checkBtnStatus: function (e) {
            //按钮状态,0为可点击,1为不可点击
            var btnStatus = $(e.target).hasClass('btn-disabled') ? 1 : 0;
            return btnStatus;

        },
        focusOnPercentInput: function () {
            //使焦点放到输入百分比输入框上
            this.$el.find('#percent-input').select();   //使input框里的值全选
        },
        checkData: function () {
            //验证
            var resultInput = this.$el.find('#result-text').val();
            var percentInput = this.$el.find('#percent-input').val();
            if (resultInput.length == 0 || percentInput.length == 0) {
                CommonTools.Toast("关键结果和关键结果占比是必填选项!");
                return false;
            }
            if (resultInput.length >= 50) {
                //超过五十字提示
                CommonTools.Toast("关键结果字数不能超过50字!");
                return false;
            }
            var reg = /^[0-9]*[1-9][0-9]*$/;
            if (!reg.test(percentInput)) {
                CommonTools.Toast("关键结果占比请输入1-100的整数!");
                return false;
            }
            else {
                if (parseInt(percentInput) > 100) {
                    CommonTools.Toast("关键结果占比请输入小于100的数字!");
                    return false;
                }
                else {
                    return true;
                }
            }

        },
        addResult: function (hasNext) {
            //hasNext用作标记是否保存并新增下一个
            var _this = this;
            var progress = this.$el.find('#percent-input').val();
            var description = this.$el.find('#result-text').val();
            var target_id = this.target_id;
            AjaxUtil.ajaxPost({
                path: '/client/keyResult/add',
                params: {
                    objectiveId: target_id,
                    description: description,
                    progress: progress
                },
                success: function (data) {
                    _this.setBegin();
                    if (hasNext) {
                        //保存并新增下一个
                        var timestamp = new Date().getTime();
                        CommonTools.Toast("保存成功!", 1000, function () {
                            _this.resetPage();
                            Backbone.history.navigate('#KeyResultAdd?target_id=' + target_id + '&timestamp=' + timestamp, {
                                trigger: true,
                                replace: true
                            });
                        });
                    } else {
                        CommonTools.Toast("保存成功!", 1000, function () {_this.back();});
                    }

                },
                error: function () {
                    CommonTools.Toast("请检查网络!");
                }
            });
        },
        editKeySave: function () {
            //编辑关键结果保存
            var _this = this;
            var progress = this.$el.find('#percent-input').val();
            var description = this.$el.find('#result-text').val();
            var target_id = this.target_id;
            var key_id = this.key_id;
            AjaxUtil.ajaxPost({
                path: '/client/keyResult/update',
                params: {
                    id: key_id,
                    objectiveId: target_id,
                    description: description,
                    progress: progress
                },
                success: function (data) {
                    _this.setBegin();
                    CommonTools.Toast("保存成功!");
                    var goalData = JSON.parse(sessionStorage.getItem("goalData"));
                    for (var i = 0; i < goalData.keyResult.length; i++) {
                        if (goalData.keyResult[i].id == key_id) {
                            goalData.keyResult[i].progress = progress;
                            goalData.keyResult[i].description = description;
                            break;
                        }
                    }
                    //本地session同步更新数据
                    sessionStorage.setItem("goalData", JSON.stringify(goalData));
                    CommonTools.Toast("保存成功!", 1000, function () {_this.back();});
                },
                error: function () {
                    CommonTools.Toast("请检查网络!");
                }
            });
        },
        saveResult: function (e) {
            if (this.checkBtnStatus(e) == 1) {
                return;
            }
            if (this.checkData()) {
                if ($(e.target).hasClass("edit-save-btn")) {
                    //编辑保存
                    this.editKeySave();
                }
                else {
                    //新增保存
                    this.addResult();
                }
            }
        },
        saveResultGoNext: function (e) {
            if (this.checkBtnStatus(e) == 1) {
                return;
            }
            if (this.checkData()) {
                this.addResult(true);
            }
        },

        back: function () {
            var _this = this;
            if (this.isChange()) {
                CommonTools.confirm("您输入的内容还未保存,确定要返回吗?", function () {
                    _this.resetPage();
                    Backbone.history.history.back();
                });
            }
            else {
                this.resetPage();
                Backbone.history.history.back();
            }
        },
        setPercent: function () {
            var _this = this;
            var goalData = JSON.parse(sessionStorage.getItem('goalData')),
                percentWord = '',
                okrsPercent = 0;

            _.each(goalData.keyResult, function (value, key) {
                okrsPercent += value.progress;
            });

            // 渲染剩余百分比
            parseInt(okrsPercent) > 100
                ? percentWord = '(超出' + (parseInt(okrsPercent) - 100) + '%)'
                : percentWord = '(剩余' + (100 - parseInt(okrsPercent)) + '%)';
            this.$el.find('.key-result-percent').html(percentWord);
        }
    });
});